package com.imageim.yimirror.ui.fragment;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.IntelligenAnalysisBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.ui.FlowlayoutTags;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.ui.dialog.PromptDialog;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.net.NetPresenterImpl;
import com.imageim.yimirror.net.NetView;
import com.imageim.yimirror.ui.adapter.ClothingAnalysisViewAdapter;
import com.imageim.yimirror.ui.widght.EmptyView;
import com.imageim.yimirror.ui.widght.LoadingView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.martin.ads.omoshiroilib.util.BitmapUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import butterknife.BindView;

/**
 * Created by Yuaihen.
 * on 2018/7/17
 * 历史分析（原智能分析）Fragment
 */
public class HistoryAnalysisFragment extends BaseFragment implements NetView, View.OnClickListener, OnRefreshListener, EmptyView.OnFinishBtnClickListener {

    private static final String TAG = "HistoryAnalysisFragment";

    @BindView(R.id.tv_cloth_style)
    TextView mTvClothingStyle;
    @BindView(R.id.flow_tags)
    FlowlayoutTags mFlowTags;
    @BindView(R.id.tv_occasion)
    TextView mTvOccasion;
    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R.id.rv_photo_list)
    RecyclerView mRvPhotoList;
    @BindView(R.id.empty_view)
    EmptyView mEmptyView;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout mSmartRefresh;
    @BindView(R.id.loading_view)
    LoadingView mLoadingView;
    @BindView(R.id.iv_photo)
    RoundedImageView mIvPhoto;
    private ClothingAnalysisViewAdapter mAdapter;
    private PromptDialog mDialog;
    private String mQrCodeUrl;
    private ImageView mIvBigQrcode;
    private NetPresenterImpl mNetPresenter;
    private List<IntelligenAnalysisBean.ClothingResultBean> mResultBeanList;
    private IntelligenAnalysisBean mIntelligenAnalysisBean;
    private int mCurrentItemPosition = 0;
    private HashMap<String, String> mDeleteMap;
    private float rate = 0.355f;
    private HashMap<String, String> mHistoryMap;
    private int deletePosition = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_history_analysis;
    }

    @Override
    protected void initListener() {
        mAdapter = new ClothingAnalysisViewAdapter(getContext(), mResultBeanList);
        mRvPhotoList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mRvPhotoList.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new ClothingAnalysisViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //将主图设置为当前选中位置的图片  其他数据同时设置为当前位置
                mCurrentItemPosition = position;
                setAnaResult(mCurrentItemPosition);
            }

            @Override
            public void onDeleteClick(int position) {
                deletePosition = position;
                if (position == mCurrentItemPosition) {
                    //删除选中的item
                    deletePhoto(true, position);
                } else {
                    //删除非选中的item
                    deletePhoto(false, position);
                }
            }

        });

        mIvQrCode.setOnClickListener(this);
        mSmartRefresh.setRefreshHeader(new MaterialHeader(mContext));
        mSmartRefresh.setOnRefreshListener(this);
        mEmptyView.setOnFinishBtnClickListener(this);
    }


    @Override
    protected void initData() {
        mNetPresenter = new NetPresenterImpl(this);
        //设置身线图的缩放比率 相对于1080*1920
        //        mBodyView.setRate(rate);
        getAnaResult();
    }

    private static final int MSG_GET_ANALYSIS = 0x0001;
    private static final int MSG_DELETE_PHOTO = 0x0002;
    private static final int MSG_DELETE_CHECK_PHOTO = 0x0003;

    /**
     * 删除对应位置的图片
     *
     * @param isCheck  是否是选中的item
     * @param position 删除的Position
     */
    private void deletePhoto(boolean isCheck, int position) {
        if (mResultBeanList == null || position >= mResultBeanList.size()) {
            return;
        }

        if (mResultBeanList.size() > 0) {
            String photoNo = mResultBeanList.get(position).getPhotoNo();
            if (!TextUtils.isEmpty(photoNo)) {
                if (mDeleteMap == null) {
                    mDeleteMap = new HashMap<>(4);
                }
                mDeleteMap.put(Constants.PHOTO_NO, photoNo);

                //TODO temp
                //                mDeleteMap.put(Constants.PHOTO_NO, "CN201812042048016FYT");
                //                mDeleteMap.put(Constants.TOKEN, "00d9b360f856435685c1187bbfd826041543927657615");
                if (isCheck) {
                    mNetPresenter.postObject(mContext, NetConstants.URL.DELETE_IMAGE_PHOTO, mDeleteMap, MSG_DELETE_CHECK_PHOTO);
                } else {
                    mNetPresenter.postObject(mContext, NetConstants.URL.DELETE_IMAGE_PHOTO, mDeleteMap, MSG_DELETE_PHOTO);
                }
            }
        }
    }

    /**
     * 获取历史分析数据
     */
    private void getAnaResult() {
        if (mHistoryMap == null) {
            mHistoryMap = new HashMap<>(4);
        }
        mHistoryMap.put(Constants.PHOTO_NO, UserUtil.getPhotoNo());

        //TODO temp
        //        mHistoryMap.put(Constants.PHOTO_NO, "CN20181206125057wRbc");
        //        mHistoryMap.put(Constants.TOKEN, "426dedecd3f2402c99b8795ae574fa4f1544071771235");
        mNetPresenter.getObject(mContext, NetConstants.URL.GET_CLOTHING_RESULT, mHistoryMap, IntelligenAnalysisBean.class, MSG_GET_ANALYSIS);
    }

    /**
     * 设置服装分析数据
     *
     * @param position 当前点击的Position
     */
    private void setAnaResult(int position) {
        if (mResultBeanList == null || mResultBeanList.size() <= 0) {
            return;
        }

        mCurrentItemPosition = position;

        IntelligenAnalysisBean.ClothingResultBean resultBean = mResultBeanList.get(position);
        if (!TextUtils.isEmpty(mIntelligenAnalysisBean.getCurrentStyleName())) {
            mTvClothingStyle.setText(MessageFormat.format("服饰风格: {0}", mIntelligenAnalysisBean.getCurrentStyleName()));
        }

        if (!TextUtils.isEmpty(resultBean.getLabels())) {
            String[] labels = resultBean.getLabels().split(",");
            mFlowTags.setTags(labels);
        }

        if (!TextUtils.isEmpty(resultBean.getShareUrl())) {
            mQrCodeUrl = resultBean.getShareUrl();
            setQrcode(mQrCodeUrl);
        }

        if (!TextUtils.isEmpty(resultBean.getOccasionNames())) {
            String[] occasionNames = resultBean.getOccasionNames().split(",");
            if (occasionNames.length > 0) {
                //只显示一个场合
                mTvOccasion.setText(occasionNames[0]);
            }
        }

        //设置主图并且显示身线点
        if (!TextUtils.isEmpty(resultBean.getUrl())) {
            GlideUtils.display(mIvPhoto, resultBean.getUrl());
            //            mBodyView.setPhoto(resultBean.getUrl());
        }
        //        Map<String, PointBean> points = resultBean.getPoints();
        //        if (points != null) {
        //            mBodyView.setRate(rate);
        //            mBodyView.setBodyData(points);
        //            mBodyView.setDrawIndicator(false);
        //            showBodyLine();
        //        } else {
        //            hideBodyLine();
        //        }
    }


    /**
     * 扫码分享
     *
     * @param url 二维码的地址
     */
    private void setQrcode(String url) {
        mIvQrCode.setImageBitmap(BitmapUtils.getQrcodeBitmapWithPadding(url, 100, Color.BLACK, 5));
    }


    /**
     * 点击二维码弹开的Dialog
     */
    private void openBigQrCode() {
        if (!TextUtils.isEmpty(mQrCodeUrl)) {
            if (mDialog == null) {
                mDialog = new PromptDialog(mContext);
                mDialog.setOutsideCanelable(true);
                mDialog.bindView(R.layout.dialog_big_qrcode, new PromptDialog.BindViewListener() {
                    @Override
                    public void onBindView(View contentView) {
                        mIvBigQrcode = contentView.findViewById(R.id.iv_bigQrCode);
                        mIvBigQrcode.setImageBitmap(BitmapUtils.getQrcodeBitmapWithPadding(mQrCodeUrl, 100, Color.BLACK, 5));
                    }
                }).show();
            } else {
                mIvBigQrcode.setImageBitmap(BitmapUtils.getQrcodeBitmapWithPadding(mQrCodeUrl, 100, Color.BLACK, 5));
                mDialog.show();
            }
        }
    }


    @Override
    public void onLoadPre(int msgCode) {
        if (msgCode == MSG_GET_ANALYSIS) {
            showLoadingView();
        }
    }

    @Override
    public void onLoadSuccess(Object result, int msgCode) {
        if (msgCode == MSG_GET_ANALYSIS) {
            mSmartRefresh.finishRefresh();
            hideLoadingView();
            hideEmptyView();
            setDataToRy(result);
        } else if (msgCode == MSG_DELETE_PHOTO || msgCode == MSG_DELETE_CHECK_PHOTO) {
            uploadPhotoNoByDelete(msgCode);
        }
    }

    /**
     * 删除照片
     *
     * @param msgCode 删除的是选中还是非选中的item
     */
    private void uploadPhotoNoByDelete(int msgCode) {
        //先移除数据
        mResultBeanList.remove(deletePosition);
        //显示动画效果
        mAdapter.notifyItemRemoved(deletePosition);
        //重新排序
        mAdapter.notifyItemRangeChanged(0, mResultBeanList.size());
        if (mResultBeanList.size() > 0) {
            //删除的是选中的图片  重新设置
            if (msgCode == MSG_DELETE_CHECK_PHOTO) {
                mAdapter.setData(mResultBeanList);
                setAnaResult(0);
            }
        } else {
            showEmptyView(false);
        }
    }


    /**
     * 设置数据到RecyclerView
     *
     * @param result 返回的数据
     */
    private void setDataToRy(Object result) {
        IntelligenAnalysisBean bean = (IntelligenAnalysisBean) result;
        if (bean != null) {
            mIntelligenAnalysisBean = bean;

            mResultBeanList = Optional.ofNullable(mIntelligenAnalysisBean.getClothingResult())
                    .orElse(new ArrayList<>());

            if (mResultBeanList.size() > 0) {
                mAdapter.setData(mResultBeanList);
                setAnaResult(0);
            } else {
                showEmptyView(false);
            }
        }
    }


    @Override
    public void onLoadFail(int errorCode, String errorMsg, int msgCode) {
        if (msgCode == MSG_GET_ANALYSIS) {
            mSmartRefresh.finishRefresh();
            hideLoadingView();
            showEmptyView(true);
        }

        toast(errorCode + errorMsg);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_qr_code) {
            openBigQrCode();
        }
    }


    /**
     * 显示空布局
     *
     * @param isError 是网络错误还是数据为空
     */
    private void showEmptyView(boolean isError) {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.VISIBLE);
            //网络错误显示刷新按钮
            if (isError) {
                mEmptyView.setErrorImg(R.drawable.ic_error);
                mEmptyView.setErrorContent("数据获取失败，请重试~");
                mEmptyView.setBtnVisiable(true);
            } else {
                mEmptyView.setErrorImg(R.drawable.ic_no_result);
                mEmptyView.setErrorContent("没有可以分析的照片~");
                mEmptyView.setBtnVisiable(false);
            }
        }
    }

    private void hideEmptyView() {
        if (mEmptyView != null) {
            if (mEmptyView.getVisibility() == View.VISIBLE) {
                mEmptyView.setVisibility(View.GONE);
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mNetPresenter != null) {
            mNetPresenter.onDestroy();
        }

        //        if (mBodyView != null) {
        //            mBodyView.destory();
        //        }
    }

    //    @Override
    //    public void onHiddenChanged(boolean hidden) {
    //        super.onHiddenChanged(hidden);
    //        if (hidden) {
    //            hideBodyLine();
    //        } else {
    //            showBodyLine();
    //        }
    //    }

    //    public void showBodyLine() {
    //        if (mBodyView != null) {
    //            mBodyView.showBodyLine();
    //        }
    //    }
    //
    //    public void hideBodyLine() {
    //        if (mBodyView != null) {
    //            mBodyView.hideBodyLine();
    //        }
    //    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (mNetPresenter != null) {
            getAnaResult();
        }
    }

    @Override
    public void onFinishBtnClick() {
        if (mNetPresenter != null) {
            getAnaResult();
        }
    }


    private void showLoadingView() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
        }
    }

    private void hideLoadingView() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
    }


    //试穿留影拍照完成 智能分析刷新数据
    @Override
    public void onEventMainThread(EventMessage event) {
        super.onEventMainThread(event);
        if (event.getCode() == EventCode.CODE_REFRESH_HISTORY) {
            if (mNetPresenter != null) {
                getAnaResult();
            }
        }
    }

}
